//
//  AddMedicationViewController.swift
//  TCMHealth
//
//  Created by 韩颖 on 2023/7/15.
//

import UIKit
import TextFieldEffects
import RxSwift
import RxCocoa
import Toast_Swift
import MJRefresh

class AddMedicationViewController: UIViewController {
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var searchTableView: UITableView!
    var medicationDic: [String: String]? = [:]
    @IBOutlet weak var medicationNameTF: IsaoTextField!
    
    @IBOutlet weak var mdicationWeight: IsaoTextField!
    
    @IBOutlet weak var addButton: UIButton!
    
    @IBOutlet weak var medicineTitleName: IsaoTextField!
    
    var page: Int = 1
    
    var searchContent = ""
    
    var saveMedicines: ((_ medicationTitleName: String,_ medications: [String: String]) -> Void)?
    
    let disposeBug = DisposeBag()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configCollectionView()
        configTableView()
        configHeadView()
    }
    
    func configHeadView(){
        Observable.combineLatest(medicationNameTF.rx.text.orEmpty, mdicationWeight.rx.text.orEmpty) {
                    textValue1, textValue2 -> Bool in
            return textValue1.count > 0 && textValue2.count > 0
                    }
                    .map { $0 }
                    .bind(to: addButton.rx.isEnabled)
                    .disposed(by: disposeBug)
        
        mdicationWeight.rx.controlEvent(.editingDidEndOnExit).subscribe(onNext: {
                   [weak self] (_) in
                   self?.mdicationWeight.resignFirstResponder()
               }).disposed(by: DisposeBag())
        
        medicationNameTF.rx.text.subscribe { content in
            if (content?.count ?? 0) > 0 {
                self.searchContent = content ?? ""
                SQLiteManger.shareManger.queryMedicineData(medicineName: content ?? "",page: self.page) {
                    self.searchTableView.isHidden = false
                    self.searchTableView.reloadData()
                }
            }else {
                self.searchTableView.isHidden = true
            }
        }.disposed(by: disposeBug)
    }
    
    @IBAction func addMedication(_ sender: Any) {
        self.medicationDic?.updateValue(mdicationWeight.text! + "g", forKey: medicationNameTF.text!)
        self.collectionView.reloadData()
        medicationNameTF.text = ""
        mdicationWeight.text = ""
        medicationNameTF.becomeFirstResponder()
        addButton.isEnabled = false
    }
    
    @IBAction func saveMedicines(_ sender: Any) {
        if (medicationDic?.keys.count ?? 0) > 0 {
            saveMedicines?(medicineTitleName.text ?? "",medicationDic!)
        }else {
            self.view.makeToast("请选择药材后保存！")
        }
        self.dismiss(animated: true)
    }
    
    func configTableView() {
        searchTableView.register(UINib.init(nibName: "SearchMedicineCell", bundle: nil), forCellReuseIdentifier: "SearchMedicineCell")
        searchTableView.mj_footer = MJRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(loadData) )
    }
    
    func configCollectionView(){
        collectionView.register(UINib.init(nibName: "MedicationCell", bundle: nil), forCellWithReuseIdentifier: "MedicationCell")
    }
    
    @IBAction func closeAction(_ sender: Any) {
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func loadData() {
        page += 1
        SQLiteManger.shareManger.queryMedicineData(medicineName: searchContent ,page: self.page) {
            self.searchTableView.mj_footer?.endRefreshing()
            self.searchTableView.reloadData()
        }
    }
}

extension AddMedicationViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.medicationDic?.keys.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: 130, height: 120)
        }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let medicationCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MedicationCell", for: indexPath) as! MedicationCell
        if (medicationDic?.keys.count ?? 0) > 0 {
            medicationCell.medicationInfo = [(Array(medicationDic!.keys)[indexPath.item] ) : (Array(medicationDic!.values)[indexPath.item] )]
        }
        medicationCell.deleteItem = {
            let key = Array(self.medicationDic!.keys)[indexPath.item]
            self.medicationDic?.removeValue(forKey: key)
            self.collectionView.reloadData()
        }
       
        return medicationCell
    }
    
}

extension AddMedicationViewController: UITableViewDelegate, UITableViewDataSource {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        medicationNameTF.resignFirstResponder()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return SQLiteManger.shareManger.searchResultArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let searchMedicineCell = tableView.dequeueReusableCell(withIdentifier: "SearchMedicineCell", for: indexPath) as! SearchMedicineCell
        if let medicationStr = SQLiteManger.shareManger.searchResultArray?[indexPath.row] {
            searchMedicineCell.medicineName = medicationStr
        }
        return searchMedicineCell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let medicationStr = SQLiteManger.shareManger.searchResultArray?[indexPath.row]
        medicationNameTF.text = medicationStr?.components(separatedBy: ",").first
        mdicationWeight.becomeFirstResponder()
        searchTableView.isHidden = true
        medicationNameTF.resignFirstResponder()
    }
}
